# https://hq.smm.cn
import parsel
import requests
import common.dataBase as db


def get_data(url):
    headers = {
        'Cookie': '__snaker__id=MhFZehVvZAd6Oohr; SMM_device_id=b311ef43-fc62-5037-9243-8750a1a83408; '
                  '_ga=GA1.2.2126302407.1648260043; SMM_session_id=6fd1e06b-74de-5f26-a504-2ea355558802; '
                  'SMM_session_start_timestamp=1657684087171; _gid=GA1.2.1738008198.1657684087; '
                  'Hm_lvt_9734b08ecbd8cf54011e088b00686939=1657684087; '
                  'Hm_lvt_50b0b45724f4f39e2a94cb8af0e9b547=1657684087; '
                  'gdxidpyhxdE=HP8GvaxLVdN%2FdE4mkztyJ8wY80vlJGvGwD1me0EuNRrMhMQNbRDTg8WmtHEBh%5CrrkHE2pBOQ3%2FS77QUB%2Bq%2B1Q%5Cx1pX5pLBdwJB29OeyoEozfDquIxgc9XlrRfceqesBMdkn6XNbjI4m1apxMiZnpcL7Apv7uVlW7Cm%5ChaOJ7ogmjGVQ2%3A1657684987741; '
                  '_9755xjdesxxd_=32; __snaker__id=QviuDWHhe5xEyxhc; referer_code=https%3A%2F%2Fhq.smm.cn%2Ftin; '
                  'SMM_auth_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjZWxscGhvbmUiOiIxMzAyNTQzNzY4OCIsImNvbXBhbnlfaWQiOjAsImNvbXBhbnlfc3RhdHVzIjowLCJjcmVhdGVfYXQiOjE2NTc2ODQyMjAsImVtYWlsIjoiIiwiZW5fZW5kX3RpbWUiOjAsImVuX3JlZ2lzdGVyX3N0ZXAiOjEsImVuX3JlZ2lzdGVyX3RpbWUiOjAsImVuX3N0YXJ0X3RpbWUiOjAsImVuX3VzZXJfdHlwZSI6MCwiZW5kX3RpbWUiOjAsImlzX21haWwiOjAsImlzX3Bob25lIjowLCJsYW5ndWFnZSI6IiIsImx5X2VuZF90aW1lIjowLCJseV9zdGFydF90aW1lIjowLCJseV91c2VyX3R5cGUiOjAsInJlZ2lzdGVyX3RpbWUiOjE2MTk0MDc0MTEsInN0YXJ0X3RpbWUiOjAsInVuaXF1ZV9pZCI6IkMzNTM3MkZBNkNFMjY3MTlBOTdDQjlCRDNFNTJCN0NBIiwidXNlcl9pZCI6MjAwMTA2MCwidXNlcl9sYW5ndWFnZSI6ImNuIiwidXNlcl9uYW1lIjoiU01NMTYxOTQwNzQxMU1xIiwidXNlcl90eXBlIjowLCJ1dWlkX3NoYTI1NiI6ImEwN2JmZjg2MTZhYzJmZDk2ZjMxOTdkYWRjYTlmZmE4OGU5MjU5NGUyMzIzMWQ3ZGQyYzRkMGExNDJjOTQyYzIiLCJ6eF9lbmRfdGltZSI6MCwienhfc3RhcnRfdGltZSI6MCwienhfdXNlcl90eXBlIjowfQ.V_NvkktJLvh2aHd23cXbLZzEybG_xgrKDhISvlR-ZI8; _gat_gtag_UA_1468766_4=1; Hm_lpvt_9734b08ecbd8cf54011e088b00686939=1657684301; Hm_lpvt_50b0b45724f4f39e2a94cb8af0e9b547=1657684302'
    }
    response = requests.get(url, headers=headers)
    # print(response.text)
    selectors = parsel.Selector(response.text)
    # #category_201102250140 > table > tbody > tr > td.average-price.font-more-big.red
    price = selectors.css('span.spot-price-average::text').get().strip()
    date = selectors.css('p.spot-info span::text').get()[5:]
    return price, date


def app(url, name):
    d = get_data(url)
    insert_sql = f'INSERT INTO mat_price VALUES (null, "{name}", "{d[0]}","", "{d[1]}", "{url}")'
    print(insert_sql)
    db.save([insert_sql])


if __name__ == "__main__":
    app('https://hq.smm.cn/tin/category/201102250140', 'SMM 1#锡')
